<template>
    <div class="notice-list" v-loading="loading">
        <common-list @resert="resert" ref="commonListRef">
            <template #message>
                <div class="message">
                    <el-descriptions column="4">
                        <el-descriptions-item label="设备编号">{{ equipmentCode == "" ? "未选择" : equipmentCode }}</el-descriptions-item>
                        <el-descriptions-item label="设备名称">{{ quipment.name == null ? "暂无" : quipment.name }}</el-descriptions-item>
                        <el-descriptions-item label="设备管理员">{{ quipment.manager == null ? "暂无" : quipment.manager }}</el-descriptions-item>
                        <el-descriptions-item label="计划周期">{{ cycleTypeName == "" ? "未选择" : cycleTypeName }}</el-descriptions-item>
                        <el-descriptions-item label="计划日期">{{ formData.execDate }}</el-descriptions-item>
                        <el-descriptions-item label="分派人员">
                            <el-select v-model="formData.personId" placeholder="请选择分派人员" style="width: 60%" :suffix-icon="CaretBottom">
                                <el-option v-for="item in personnel" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-descriptions-item>
                        <el-descriptions-item label=""></el-descriptions-item>
                        <el-descriptions-item label="">
                            <el-button class="switchover" @click="frontClick" :ref="frontChange">{{ front }}</el-button>
                            <el-button class="switchover" @click="laterClick" :ref="laterChange">{{ later }}</el-button>
                        </el-descriptions-item>
                    </el-descriptions>
                </div>
            </template>
            <template #ItemCount="{ scope }">
                <div style="color: #0081e3; cursor: pointer" @click="lineClick(scope)">{{ scope.scope.row.itemCount }}</div>
            </template>
            <template #operate="{ scope }">
                <el-button v-if="scope.scope.row.state != 3" link type="primary" size="small" @click="dateChange(scope)">修改日期</el-button>
            </template>
            <template #btns>
                <div class="btns1">
                    <text class="first" @click="firstMaintain"> 一级保养 </text>
                    <text class="second"> 二级保养 </text>
                </div>
                <div class="btns">
                    <w-button class="config-btn" @click="dateBatchChange()">一键修改日期</w-button>
                </div>
            </template>
            <template #StructureName="{ scope }">
                <div :class="[scope.scope.row.state == 3 ? 'useless' : '']">{{ scope.scope.row.structureName }}</div>
            </template>
        </common-list>
        <!-- 操作(修改日期) -->
        <el-dialog v-model="amend" v-if="amend" title="修改日期" width="25%" :close-on-click-modal="false">
            <el-form :label-position="labelPosition" label-width="80px" :model="dataTime" :rules="Rules" ref="RuleFormRef" style="max-width: 460px">
                <el-form-item label="日期" prop="targetDate">
                    <el-date-picker v-model="dataTime.targetDate" type="date" placeholder="请选择日期" value-format="YYYY-MM-DD" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="amend = false">取消</el-button>
                    <el-button type="primary" @click="amendSubmit(RuleFormRef)">确认</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 操作(批量修改日期) -->
        <el-dialog v-model="amendBatch" v-if="amendBatch" title="修改日期" width="25%" :close-on-click-modal="false">
            <el-form :label-position="labelPosition" label-width="80px" :model="dataBatchTime" :rules="Rules" ref="RuleFormRef" style="max-width: 460px">
                <el-form-item label="日期" prop="targetDate">
                    <el-date-picker v-model="dataBatchTime.targetDate" type="date" placeholder="请选择日期" value-format="YYYY-MM-DD" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="amendBatch = false">取消</el-button>
                    <el-button type="primary" @click="amendBatchSubmit(RuleFormRef)">确认</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 操作(详情) -->
        <el-dialog v-model="detail" title="" width="50%" :close-on-click-modal="false">
            <div class="card-header">
                <span>{{ editFormData.structureTypeText }}-{{ editFormData.structureName }} (检查项：{{ editFormData.itemCount }})</span>
            </div>
            <el-table :data="editFormData.itemDetails" height="400" style="width: 100%">
                <el-table-column type="index" label="序号" min-width="50" />
                <el-table-column prop="location" label="位置" min-width="120" />
                <el-table-column prop="itemName" label="检查项" min-width="220" />
            </el-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="detail = false">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { provide, reactive, ref } from "vue";
import { CaretBottom } from "@element-plus/icons-vue";
import { formConfig, tableConfig, Rules } from "./secondConfig";
import { getMaintain, getPlanType, getPersonnel, getQuipment, setDate, setBatchDate } from "@/service/api/planManagement.js";
import { useRoute, useRouter } from "vue-router";

const loading = ref(false);
const route = useRoute();
const router = useRouter();
const commonListRef = ref(null);
const personnel = ref();
const quipment = ref({});
const front = ref();
const later = ref();
const amend = ref(false);
const amendBatch = ref(false);
const RuleFormRef = ref();
const dataTime = ref();
const dataBatchTime = ref();
const nowTime = ref(new Date(new Date().toDateString()).getTime());
const detail = ref(false);
const editFormData = ref();
const equipmentCode = ref(route.query.equipmentCode);
const cycleTypeName = ref(route.query.cycleTypeName);
const personId = ref();
const formData = reactive({
    equipmentId: route.query.equipmentId,
    planCycleType: route.query.planCycleType,
    execDate: route.query.execDate,
    maintenanceType: route.query.maintenanceType,
    structureType: "",
    structureName: "",
    personId: personId.value
});

const firstMaintain = () => {
    router.push({
        path: "/main/planManagement/firstMaintain",
        query: {
            execDate: formData.execDate,
            equipmentId: formData.equipmentId,
            planCycleType: formData.planCycleType,
            maintenanceType: 1,
            equipmentCode: equipmentCode.value,
            cycleTypeName: cycleTypeName.value
        }
    });
};

const frontChange = () => {
    if (formData.planCycleType == 1) {
        front.value = "前一周";
    } else if (formData.planCycleType == 2) {
        front.value = "前一月";
    } else if (formData.planCycleType == 3) {
        front.value = "前一季";
    } else if (formData.planCycleType == 4) {
        front.value = "前一年";
    } else {
        front.value = "前一天";
    }
};
const laterChange = () => {
    if (formData.planCycleType == 1) {
        later.value = "后一周";
    } else if (formData.planCycleType == 2) {
        later.value = "后一月";
    } else if (formData.planCycleType == 3) {
        later.value = "后一季";
    } else if (formData.planCycleType == 4) {
        later.value = "后一年";
    } else {
        later.value = "后一天";
    }
};
const frontClick = () => {
    if (front.value == "前一周") {
        formData.execDate = dateAddDays(formData.execDate, -7);
    } else if (front.value == "前一月") {
        formData.execDate = dateAddDays(formData.execDate, -30);
    } else if (front.value == "前一季") {
        formData.execDate = dateAddDays(formData.execDate, -90);
    } else if (front.value == "前一年") {
        formData.execDate = dateAddDays(formData.execDate, -365);
    } else {
        formData.execDate = dateAddDays(formData.execDate, -1);
    }
    commonListRef.value.tableRef.getTableList();
};
const laterClick = () => {
    if (later.value == "后一周") {
        formData.execDate = dateAddDays(formData.execDate, 7);
    } else if (later.value == "后一月") {
        formData.execDate = dateAddDays(formData.execDate, 30);
    } else if (later.value == "后一季") {
        formData.execDate = dateAddDays(formData.execDate, 90);
    } else if (later.value == "后一年") {
        formData.execDate = dateAddDays(formData.execDate, 365);
    } else {
        formData.execDate = dateAddDays(formData.execDate, 1);
    }
    commonListRef.value.tableRef.getTableList();
};
function dateAddDays(dateStr, dayCount) {
    let tempDate = new Date(dateStr.replace(/-/g, "-")); //把日期字符串转换成日期格式
    let resultDate = new Date((tempDate / 1000 + 86400 * dayCount) * 1000); //增加n天后的日期
    let resultDateStr =
        resultDate.getFullYear() +
        "-" +
        (resultDate.getMonth() + 1 < 10 ? "0" + (resultDate.getMonth() + 1) : resultDate.getMonth() + 1) +
        "-" +
        (resultDate.getDate() < 10 ? "0" + resultDate.getDate() : resultDate.getDate()); //将日期转化为字符串格式
    return resultDateStr;
}
getPlanType().then((res) => {
    if (res.code === 200) {
        formConfig[0].options = res.data.map((item) => ({
            label: item.name,
            value: item.value
        }));
    }
});
function Quipment() {
    if (formData.equipmentId == null || formData.equipmentId == "") {
        getQuipment({ equipmentId: 0 }).then((res) => {
            if (res.code === 200) {
                quipment.value = res.data;
            }
        });
    } else {
        getQuipment({ equipmentId: formData.equipmentId }).then((res) => {
            if (res.code === 200) {
                quipment.value = res.data;
            }
        });
    }
}
function Personnel() {
    if (formData.equipmentId == null || formData.equipmentId == "") {
        getPersonnel({ equipmentId: 0 }).then((res) => {
            if (res.code === 200) {
                personnel.value = null;
            }
        });
    } else {
        getPersonnel({ equipmentId: formData.equipmentId }).then((res) => {
            if (res.code === 200) {
                personnel.value = res.data.map((item) => ({
                    label: item.name,
                    value: item.value
                }));
            }
        });
    }
}
Quipment();
Personnel();
const dateChange = (scope) => {
    amend.value = true;
    dataTime.value = {
        planDetailId: scope.scope.row.id,
        targetDate: ""
    };
};
const amendSubmit = () => {
    if (!RuleFormRef.value) return;
    RuleFormRef.value
        .validate((valid) => {
            if (valid) {
                dataTime.value.targetDate = dataTime.value.targetDate.substring(0, 19);
                dataTime.value.targetDate = dataTime.value.targetDate.replace(/-/g, "-");
                const modifiedTime = new Date(dataTime.value.targetDate).getTime();
                formData.execDate = formData.execDate.substring(0, 19);
                formData.execDate = formData.execDate.replace(/-/g, "-");
                const planTime = new Date(formData.execDate).getTime();
                console.log(modifiedTime, nowTime.value);
                if (modifiedTime === planTime) {
                    ElMessage.warning("修改日期不能等于计划日期，请重新操作！");
                } else if (modifiedTime < nowTime.value) {
                    ElMessage.warning("修改日期不能小于当前时间，请重新操作！");
                } else {
                    const loadingInstance = ElLoading.service();
                    setDate(dataTime.value).then((res) => {
                        loadingInstance.close();
                        if (res.code === 200) {
                            amend.value = false;
                            ElMessage.success("修改成功！");
                            commonListRef.value.tableRef.getTableList();
                        } else {
                            amend.value = false;
                            ElMessage.error(res.message);
                        }
                    });
                }
            }
        })
        .catch((err) => {
            loading.value = false;
        });
};

const dateBatchChange = () => {
    const BeamendBatch = commonListRef.value.tableRef.tableData.map((item) => item.state);
    if (BeamendBatch.indexOf("1") === -1) {
        ElMessage.warning("当前日期无可修改日期的计划！");
    } else {
        amendBatch.value = true;
        dataBatchTime.value = {
            execDate: formData.execDate,
            targetDate: ""
        };
    }
};
const amendBatchSubmit = () => {
    if (!RuleFormRef.value) return;
    RuleFormRef.value
        .validate((valid) => {
            if (valid) {
                dataBatchTime.value.targetDate = dataBatchTime.value.targetDate.substring(0, 19);
                dataBatchTime.value.targetDate = dataBatchTime.value.targetDate.replace(/-/g, "-");
                const modifiedTime = new Date(dataBatchTime.value.targetDate).getTime();
                formData.execDate = formData.execDate.substring(0, 19);
                formData.execDate = formData.execDate.replace(/-/g, "-");
                const planTime = new Date(formData.execDate).getTime();
                if (modifiedTime === planTime) {
                    ElMessage.warning("修改日期不能等于计划日期，请重新操作！");
                } else if (modifiedTime < nowTime.value) {
                    ElMessage.warning("修改日期不能小于当前时间，请重新操作！");
                } else {
                    const loadingInstance = ElLoading.service();
                    setBatchDate(dataBatchTime.value).then((res) => {
                        loadingInstance.close();
                        if (res.code === 200) {
                            amendBatch.value = false;
                            ElMessage.success("修改成功！");
                            commonListRef.value.tableRef.getTableList();
                        } else {
                            amendBatch.value = false;
                            ElMessage.error(res.message);
                        }
                    });
                }
            }
        })
        .catch((err) => {
            loading.value = false;
        });
};
const resert = () => {
    Object.keys(formData).forEach((key) => {
        if (key !== "equipmentId" && key !== "planCycleType" && key !== "execDate" && key !== "maintenanceType") {
            formData[key] = "";
        }
    });
};
const lineClick = (scope) => {
    editFormData.value = scope.scope.row;
    detail.value = true;
};
provide("formConfig", formConfig);
provide("tableConfig", tableConfig);
provide("formData", formData);
provide("apiFn", getMaintain);
</script>

<style lang="less" scoped>
.notice-list {
    :deep(.el-input__wrapper) {
        width: 100%;
    }
    .card-header {
        font-size: 16px;
        font-weight: 600;
        color: #1b3646;
        line-height: 22px;
        margin-top: -40px;
        padding-bottom: 20px;
    }
    .message {
        height: 112px;
        background: #ffffff;
        margin-bottom: 20px;
        :deep(.el-descriptions) {
            padding: 28px 20px 0 20px;
        }
    }
    .useless {
        text-decoration: line-through;
    }
    .btns1 {
        position: absolute;
        .first {
            color: #8c8c8c;
            font-size: 16px;
            cursor: pointer;
        }
        .second {
            color: #1b3646;
            font-size: 16px;
            margin-left: 25px;
        }
    }
    .btns {
        display: flex;
        .resert {
            border: 1px solid @main-color;
            color: @main-color;
        }
        .config-btn {
            width: 110px;
        }
    }
    .switchover {
        border: 1px solid #00428e;
        color: #00428e;
        font-size: 14px;
    }
}
</style>
<style>
.el-descriptions__cell:last-child {
    display: flex;
    justify-content: flex-end;
}
</style>
